package com.cstp.manage;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.cstp.web.res.PhpTokenResp;
import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author watts
 */
@Component
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class WxMpManage {

    @Value("${wx.tmpId:wuIkZabsyz_GfoCGxig1RoBLkVTFl7d87asX3gbSeJ8}")
    String tmpId;

    @Value("${wx.jumpUrl:http://cstp.liangdonghui.cn/home/poster?name=$}")
    String jumpUrl;

    @Value("${wx.lotteryTmpId:fPE_fBujyFaorDB3yU-mUAoShvMFManncEICia6FYU4}")
    String lotteryTmpId;

    @Resource
    private WxMpService wxMpService;

    @SneakyThrows
    public String getToken() {
        return wxMpService.getAccessToken();
    }

    @SneakyThrows
    public String getTicket() {
        return wxMpService.getJsapiTicket();
    }

    /**
     * 取长沙交警pho服务token
     *
     * @return
     */
    @SneakyThrows
    public String getPhpToken() {
        PhpTokenResp result = JSONUtil.toBean(HttpUtil.get("http://web.csjj.1678c.com/reception/api/gettoken?key=8918QbhRkQdKNsxBky7TTfEbsv9PR3qwxv6ZeRf[d]ES6qxq[d]mZgcfZGXq4n[a]DHC[a]GsUP1IZeMPd5tPjGCjPM[s]"), PhpTokenResp.class);
        if (!"success".equals(result.getDesc())) {
            log.error("get pho token failed");
        }
        String token = result.getData().getToken();
        log.info("get pho token successfully token : [{}]", token);
        return token;
    }

    @SneakyThrows
    public String getAccessToken(String code) {
        return wxMpService.getOAuth2Service().getAccessToken(code).getOpenId();
    }

    @SneakyThrows
    public void sendTemplateMessage(String toUser, String url, Map<String, Map<String, String>> data, String tmpId) {
        Map<String, Object> json = new HashMap<>(4);
        json.put("touser", toUser);
        json.put("template_id", tmpId);
        json.put("url", url);
        json.put("data", data);
        String result = HttpUtil
                .createPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" +
                        this.getPhpToken())
                .body(JSONUtil.toJsonStr(json), "application/json; charset=utf-8")
                .execute()
                .body();
        log.info("send template msg result {}", result);
    }

    @Async
    @SneakyThrows
    public void sendLotteryMsg(String toUser, String prizeName) {
        Map<String, Map<String, String>> data = new HashMap<>(4);
        Map<String, String> first = Maps.newHashMap();
        first.put("value", "您好，恭喜您已抽到奖品，快去线下兑换吧");
        data.put("first", first);

        Map<String, String> keyword1 = Maps.newHashMap();
        keyword1.put("value", prizeName);
        data.put("keyword1", keyword1);

        Map<String, String> keyword2 = Maps.newHashMap();
        keyword2.put("value", DateUtil.now());
        data.put("keyword2", keyword2);

        Map<String, String> remark = Maps.newHashMap();
        remark.put("value", "获奖人在活动期间的工作日内，自行到长沙交警大楼（枫林一路2号，湘江橘子洲大桥西）912办公室领取，联系电话：0731-88878920。");
        data.put("remark", remark);
        this.sendTemplateMessage(toUser, null, data, lotteryTmpId);
    }

    @Async
    @SneakyThrows
    public void sendReportApprovedMsg(String toUser, String uname, String content) {
        Map<String, Map<String, String>> data = new HashMap<>(4);
        Map<String, String> first = Maps.newHashMap();
        first.put("value", "您好，您的志愿者申请已通过，领取您的海报吧");
        data.put("first", first);

        Map<String, String> keyword1 = Maps.newHashMap();
        keyword1.put("value", content);
        data.put("keyword1", keyword1);

        Map<String, String> keyword2 = Maps.newHashMap();
        keyword2.put("value", "已通过");
        data.put("keyword2", keyword2);

        Map<String, String> remark = Maps.newHashMap();
        remark.put("value", "感谢您的反馈，让大家的“返乡之路”一路畅通！");
        data.put("remark", remark);
        this.sendTemplateMessage(toUser, jumpUrl.replace("$", uname), data, tmpId);
        log.info(JSONUtil.toJsonStr(data));
    }
}
